package top.laoshuzi.server.userservice.utils.config;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    private static final String DEFAULT_PATH = "/swagger";

    @Bean
    public Docket createRestApiClient() {
        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(Collections.singletonList(securityScheme()))
                .securityContexts(Collections.singletonList(securityContext()))
//                .globalOperationParameters(setToken())
                .apiInfo(apiInfo())
                .groupName("user-service")
                .select()
                .apis(RequestHandlerSelectors.basePackage("top.laoshuzi.server.userservice"))
//                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    SecurityScheme securityScheme() {
        return new ApiKey("JWT", "Authorization", "header");
    }

    @Bean
    SecurityContext securityContext() {
        SecurityReference securityReference = SecurityReference.builder()
                .reference("JWT")
                .scopes(new AuthorizationScope[]{})
                .build();
        return SecurityContext.builder()
                .securityReferences(Collections.singletonList(securityReference))
                .forPaths(
                        Predicates.and(
                                Predicates.not(PathSelectors.regex("/v[0-9]+/session")),
                                Predicates.not(PathSelectors.regex("/v[0-9]+/session/oauth")),
                                Predicates.not(PathSelectors.regex("/v[0-9]+/sms")))
                )
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API文档")
                .description("微服务测试")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }

}
